/**
 * problem_014.c
 * Copyright (C) 2011-03-18 - xrose
 * Collatz problem
 */

#include <stdio.h>
#include <math.h>
#include <gmp.h>
#define maxsize 1000000

int collatz(unsigned int colz);
int main (int argc, char *argv[])
{
    register unsigned int i;
    int mcollatz = 0;
    int tmp = 0;
    for(i=2; i<maxsize; i++)
    {
        tmp = collatz(i);
        if(mcollatz<tmp)
        {
            mcollatz = tmp;
            printf("mcollatz__%d__number__%d\n", mcollatz, i);
        }
    }
    printf("__%d\n", collatz(670617279));
    printf("Answer is: %d\n", mcollatz);
    return 0;
}

int collatz(unsigned int colz)
{
    //Input: a starting collatz number
    //Output: number of the collatz sequence
    register int count = 0;
//    unsigned long long n_colz = colz;
    mpz_t n_colz;
    mpz_init(n_colz);
    mpz_set_ui(n_colz, colz);
    do
    {
        count++;
//        printf("_%d__%d\n", count, n_colz);
        if(!mpz_divisible_ui_p(n_colz, 2))
        {
            //n_colz = 3*n_colz+1
            mpz_mul_ui(n_colz, n_colz, 3);
            mpz_add_ui(n_colz, n_colz, 1);
        } else
        {
            //n_colz=n_colz/2;
            mpz_divexact_ui(n_colz, n_colz, 2);
        }
    } while (mpz_cmp_ui(n_colz,1));
    return count + 1;
}
